package com.taotao.rest.service;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.taotao.common.pojo.TaotaoResult;
import com.taotao.common.utils.JsonUtils;
import com.taotao.mapper.TbContentMapper;
import com.taotao.pojo.TbContent;
import com.taotao.pojo.TbContentExample;
import com.taotao.pojo.TbContentExample.Criteria;
import com.taotao.rest.component.JedisClient;
@Service
public class ContentServiceImpl implements ContentService {
	@Autowired
	private TbContentMapper tbContentMapper;
	@Autowired
	private JedisClient jedisClient;
	@Value("${REDIS_CONTENT_KEY}")
	private String REDIS_CONTENT_KEY;

	public TaotaoResult getContentList(long cid) {
		// 请求内容服务前对Redis缓存判断key是否存在值,有直接获取缓存数据,没有再查数据库
		try {
			String contents = jedisClient.hget(REDIS_CONTENT_KEY, cid + "");
			if (!StringUtils.isBlank(contents)) {
				return TaotaoResult.ok(JsonUtils.jsonToList(contents,
						TbContent.class));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		TbContentExample example = new TbContentExample();
		Criteria criteria = example.createCriteria();
		criteria.andCategoryIdEqualTo(cid);
		List<TbContent> list = tbContentMapper
				.selectByExampleWithBLOBs(example);
		// 数据库查到数据后先加入到redis缓存中,再进行返回(方便重复获取内容数据)
		try {
			jedisClient.hset(REDIS_CONTENT_KEY, cid + "",
					JsonUtils.objectToJson(list));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return TaotaoResult.ok(list);
	}

	/**
	 * 同步redis缓存的内容,后台每次更新内容后调用该方法,清除redis对应key内容
	 */
	public TaotaoResult syncContent(long cid) {
		jedisClient.hdel(REDIS_CONTENT_KEY, cid + "");
		return TaotaoResult.ok();
	}
}
